package com.example.musicserver.service;

import com.example.musicserver.mapper.LoveMusicMapper;
import com.example.musicserver.mapper.MusicMapper;
import com.example.musicserver.model.Music;
import com.example.musicserver.model.User;
import com.example.musicserver.tools.Constant;
import com.example.musicserver.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2022-08-11
 * Time: 10:55
 */
@Service
public class MusicService {
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;
    @Value("${music.local.path}")
    private String SAVE_PATH;
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam(value = "filename") MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response) throws IOException {


        HttpSession session = request.getSession(false);
        InputStream is = file.getInputStream();
        InputStreamReader isReader = new InputStreamReader(is, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isReader);
        //循环逐行读取
        String line;
        boolean flg = false;
        while ((line = br.readLine()) != null) {
            if(line.contains("TAG")){
                flg = true;
            }
        }

        br.close();

        if(flg == false){
            return new ResponseBodyMessage<>(-1, "文件格式错误", false);
        }

        //获取文件名 xx.mp3
        String fileNameAndType = file.getOriginalFilename();
        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0, index);

        Music music = musicMapper.select(title,singer);

        if(music != null){
            return new ResponseBodyMessage<>(-1, "已有同名同歌手的歌曲", false);
        }

        System.out.println("fileName：" + fileNameAndType);
        String path = SAVE_PATH + fileNameAndType;

        File dest = new File(path);

        if (!dest.exists()) {
            dest.mkdir();
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "上传失败", false);
        }

        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId = user.getId();

        String url = "/music/get?path=" + title;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());


        int ret = 0;
        ret = musicMapper.insert(title, singer, time, url, userId);

        if (ret == 1) {
            response.sendRedirect("/index.html");
            return new ResponseBodyMessage<>(0, "上传成功", true);
        } else {
            return new ResponseBodyMessage<>(-1, "上传失败", false);
        }
    }

    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String name){
        List<Music> music = null;
        if(name == null){
            music = musicMapper.findMusic();
        }else {
            music = musicMapper.findMusicByName(name);
        }

        return new ResponseBodyMessage<>(0,"查找成功",music);
    }

    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        int id1 = Integer.parseInt(id);
        Music music = musicMapper.selectById(id1);
        //检测要删除的 音乐 是否存在
        if(music == null){
            return new ResponseBodyMessage<>(-1,"没有此音乐，无法删除",false);
        }

        //进行数据库删除
        int ret = 0;
        ret = musicMapper.deleteById(id1);

        if(ret == 1){
            //数据库删除后 再进行服务器的删除
            File file = new File(SAVE_PATH + "/" + music.getTitle() + ".mp3");
            if(file.delete()){
                loveMusicMapper.deleteLoveMusicBymusicId(music.getId());
                return new ResponseBodyMessage<>(0,"服务器删除成功",true);
            }else{
                return new ResponseBodyMessage<>(0,"服务器删除失败",true);
            }
        }else{
            return new ResponseBodyMessage<>(-1,"删除失败",false);
        }
    }

    public ResponseEntity<byte[]> func(String path){
        File file = new File(SAVE_PATH + "/" + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id){
        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            Music music = musicMapper.selectById(id.get(i));
            if(music == null){
                return new ResponseBodyMessage<>(-1,"没有此音乐，无法删除",false);
            }

            //进行数据库删除
            int ret = 0;
            ret = musicMapper.deleteById(id.get(i));
            if(ret == 1){
                //数据库删除后 再进行服务器的删除
                File file = new File(SAVE_PATH + "/" + music.getTitle() + ".mp3");
                if(file.delete()){
                    sum += ret;
                    loveMusicMapper.deleteLoveMusicBymusicId(music.getId());
                }else{
                    return new ResponseBodyMessage<>(0,"批量删除失败",true);
                }
            }else{
                return new ResponseBodyMessage<>(-1,"批量删除失败",false);
            }
        }

        if(sum == id.size()){
            return new ResponseBodyMessage<>(0,"服务器删除成功",true);
        }else{
            return new ResponseBodyMessage<>(0,"批量删除失败",false);
        }
    }
}
